﻿using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace TestConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("------------------------------------单层json---------------------------------");
            GetJsonObject();
            Console.WriteLine("------------------------------------多层json---------------------------------");
            GetJsonClass();
            Console.Read();
        }
        /// <summary>
        /// 单层jsson数据{name:"",age:""}
        /// </summary>
        /// <returns></returns>
        public static void GetJsonObject()
        {
            var jsonstr = "{name:\"陶伟\",age:\"20\"}";
            JObject jo = (JObject)JsonConvert.DeserializeObject(jsonstr);
            Console.WriteLine(jsonstr);
            //取值,直接对象["属性名"]
            Console.WriteLine(jo["name"]);
            Console.WriteLine(jo["age"]);

        }
        /// <summary>
        /// 多层json使用类序列化即可,（注意,使用自定义类解析时候,类属性必须和json字符串的属性一致）
        /// </summary>
        public static void GetJsonClass()
        {
            var jsonstr = "{name:\"陶伟\",age:\"20\",data:[{kemu:\"语文\",sorce:\"100\"},{kemu:\"数学\",sorce:\"98\"},{kemu:\"英语\",sorce:\"88\"}]}";
            Console.WriteLine(jsonstr);
            var obj = JsonConvert.DeserializeObject<jsonClass>(jsonstr);
            Console.WriteLine($"姓名:{obj.name},年龄{obj.age}");
            foreach (var x in obj.data)
            {
                Console.WriteLine($"科目:{x.kemu},分数{x.sorce}");
            }
        }
    }

    class jsonClass
    {
        public string name { get; set; }
        public string age { get; set; }
        public List<dataList> data { get; set; }

        public class dataList
        {
            public string kemu { get; set; }
            public string sorce { get; set; }
        }
    }
}
